//
//  UIViewController+Additions.swift
//  live
//
//  Created by melvyn on 2018/8/18.
//  Copyright © 2018 NEET. All rights reserved.
//

import UIKit
import RxSwift
import ObjectiveC.runtime

extension UIViewController {
    
    var viewWillAppear: Observable<Void> {
        return rx.methodInvoked(#selector(UIViewController.viewWillAppear(_:))).map { _ in }
    }
    
    var viewWillDisappear: Observable<Void> {
        return rx.methodInvoked(#selector(UIViewController.viewWillDisappear(_:))).map { _ in }
    }
    
    var isViewDidAppear: Observable<Bool> {
        return Observable.merge([
            viewDidDisappear.map { false },
            viewDidAppear.map { true }
            ])
    }
    
    var viewDidAppear: Observable<Void> {
        return rx.methodInvoked(#selector(UIViewController.viewDidAppear(_:))).map({ _ in })
    }
    
    var viewDidDisappear: Observable<Void> {
        return rx.methodInvoked(#selector(UIViewController.viewDidDisappear(_:))).map { _ in }
    }
}


extension UIViewController {
    
    private struct AssociatedKeys {
        static var disposeBag = "Rx.UIViewController_disposeBag_associatedKey"
    }
    
    var disposeBag: DisposeBag {
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.disposeBag, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get {
            guard let disposeBag = objc_getAssociatedObject(self, &AssociatedKeys.disposeBag) as? DisposeBag else {
                let disposeBag = DisposeBag()
                objc_setAssociatedObject(self, &AssociatedKeys.disposeBag, disposeBag, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
                return disposeBag
            }
            return disposeBag
        }
    }
}

